#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>

#include <sys/stat.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <fcntl.h>
#include <linux/fs.h>

#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/param.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/select.h>

#include <libaio.h>

#include "bmap.h"

//****************************************************************************************

struct bmap * bmap_fetch(const char *filename)
{
	struct bmap *bm;
	struct stat fi;
	uint64_t fblkcnt, i;
	int fd;
	assert(filename!=NULL);
	if(stat(filename, &fi)<0){
		perror("bmap_fetch stat failed!");
		exit(-1);
	}
	//printf("%s's size      is %-4d bytes\n", filename, fi.st_size);
    //printf("%s's t_blksize is %-4d bytes\n", filename, fi.st_blksize);
    //printf("%s's blocks    is %-4d blocks\n", filename, fi.st_blocks);
	bm = bmap_create(filename, fi.st_blksize);
	fblkcnt = (fi.st_size + fi.st_blksize - 1)/fi.st_blksize;
	if((fd = open(filename, O_RDONLY))<0){
		perror("bmap_fetch open failed!");
		exit(-1);
	}
	for(i=0; i<fblkcnt; i++){
		uint64_t address=i;
		if(ioctl(fd, FIBMAP, &address)<0){
			perror("bmap_fetch FIBMAP failed!");
			exit(-1);
		}
		bmap_append(bm, address, 1);
	}
	close(fd);
	return bm;
}



//*****************************************************************************************



